package com.oren.base;

import com.oren.config.DatabaseHelper;
import com.oren.util.EntityUtil;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: wangshiwei
 * Date: 2018/7/13
 * Time: 16:06
 * describe:
 */
public class SqlDaoImpl<T> implements SqlDao<T>{

    private final static Logger LOGGER= LoggerFactory.getLogger(SqlDao.class);

    /**
     * 根据相关参数查询数据，并返回实体类
     * @param entity
     * @param sql 传入的sql语句
     * @param params 传入的参数
     * @return 返回list集合的实体类
     */
    public  List<T> queryEntity(Class<T> entity, String sql, Object... params){
        List<T> entityList;
        Connection connection= DatabaseHelper.getConnection();
        try {
            LOGGER.debug("数据库操作开始~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            LOGGER.debug("输入参数为："+params);
            entityList=DatabaseHelper.QUERY_RUNNER.query(connection,sql,new BeanListHandler<T>(entity),params);
            LOGGER.debug("返回的数据长度为："+entityList.size());
            LOGGER.debug("返回的数据为（取前10条）");
            for (T t:entityList) {
                LOGGER.debug(t.toString());
            }
        } catch (SQLException e) {
            LOGGER.error("query entity list failure",e);
            throw new RuntimeException(e);
        }
        LOGGER.debug("数据库操作结束~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        return entityList;
    }



    /**
     *
     * @param entity
     * @param //filemap
     */
    public  boolean insertEntity(T entity){
        return excuteUpdate(EntityUtil.getInsertEntitySql(entity))==1;
    }

    /**
     * 修改数据
     * @param entity
     * @param str
     * @return
     */
    public  boolean updateEntity(T entity,String[] str){
        int row=excuteUpdate(EntityUtil.getUpdateEntitySql(entity,str));
        if(row<1){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 执行sql语句，返回受影响的行数
     * @param sql
     * @param objects
     * @return
     */
    public  static  int excuteUpdate(String sql,Object...objects){
        int rows=0;
        try {
            Connection connection=DatabaseHelper.getConnection();
            rows=DatabaseHelper.QUERY_RUNNER.update(connection,sql,objects);
        }catch (SQLException e){
            LOGGER.error("excute update failure",e);
            throw  new RuntimeException(e);
        }
        LOGGER.debug("受影响的行数为："+rows);
        return rows;
    }

    /**
     *  删除数据
     * @param entity
     * @param columnStr
     * @return
     */
    public boolean deleteEntity(T entity,String[] columnStr){
        int row=excuteUpdate(EntityUtil.getDeleteEntitySql(entity,columnStr));
        if(row<1){
            return false;
        }else {
            return true;
        }
    }

}
